package cn.wolfcode.service.impl;

import cn.wolfcode.domain.User;
import cn.wolfcode.mapper.UserMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.utils.Constants;
import cn.wolfcode.vo.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    private final UserMapper mapper;

    public UserServiceImpl(UserMapper mapper) {
        this.mapper = mapper;
    }

//    @Override
//    public Page<User> query(QueryObject qo) {
//        Long total = mapper.selectForCount(qo);
//        if (total == 0) {
//            return Page.empty(qo.getCurrent(), qo.getLimit());
//        }
//        List<User> list = mapper.selectForList(qo);
//        return new Page<>(qo.getCurrent(), qo.getLimit(), total, list);
//    }
    @Override
    public Page<User> query(QueryObject qo) {
        System.out.println("qo = " + qo);
        Long total = mapper.selectForCount(qo);
        System.out.println("total = " + total);
        if (total == 0) {
            return Page.empty(qo.getCurrent(), qo.getLimit());
        }
        List<User> users = mapper.selectForList(qo);
        return new Page<>(qo.getCurrent(), qo.getLimit(), total, users);
    }

    @Override
    public void save(User obj) {
        if (!StringUtils.hasText(obj.getPassword())){
            obj.setPassword(Constants.DEFAULT_USER_PASSWORD);
        }
        if (!StringUtils.hasText(obj.getAvatar())){
            obj.setAvatar(Constants.DEFAULT_USER_AVATAR);
        }
        //TODO 数据不要写死 去实体类修改
        obj.setStatus(User.STATUS_NORMAL);
        obj.setDeleted(User.NO_DELETE);
        mapper.insert(obj);
    }

    @Override
    public void updateById(User obj) {
        mapper.updateByPrimaryKey(obj);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public User findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> findAll() {
        return mapper.selectAll();
    }

    @Override
    public void changeStatus(Long id, String status) {
        mapper.changeStatus(id,status);
    }

    @Override
    public void logicDeleteById(Long id, boolean deleted) {
        mapper.logicDeletById(id,deleted);
    }
}
